<template>
  <section>
    <el-row>
      <draggable :list="list" v-bind="$attrs">
        <el-col v-for="(item,i) in list" :span="6">
          <section class="v-img-item">
            <el-image :src="item.pic" fit="contain" @click="setPic(i,item)">
              <div slot="error" class="image-slot" @click="setPic(i,item)">
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
            <section class="del-img" @click="delImg4list(i)">
              <img src="./delete.png" alt="">
            </section>
          </section>
        </el-col>
      </draggable>
      <el-col :span="6">
        <section class="add-img" @click="addImg"><i class="el-icon-plus" /></section>
      </el-col>
    </el-row>

    <!--设置图片内容-->
    <el-dialog
      v-if="linkFlag"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="visible"
      title="设置图片"
      center
      :before-close="() =>{visible = false}"
    >
      <el-form ref="form" :model="form" label-width="80px" style="max-height: 500px;overflow-y: auto" :rules="rules">
        <el-form-item label="图片来源">
          <el-radio-group v-model="form.source" @change="sourceChange">
            <el-radio :label="1">本地上传</el-radio>
            <el-radio :label="2">图片库选取</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="pic">
          <template>
            <div class="form-uploader" @click="setFormPic">
              <el-image :src="form.pic">
                <div slot="error" class="image-slot my-slot">
                  <template>
                    <div class="icon-wrap">
                      <i class="el-icon-plus avatar-uploader-icon" style="font-size:28px;" />
                    </div>
                  </template>
                </div>
              </el-image>
            </div>
            <image-no-cropper-upload
              v-if="uploadFile.showUpload===2"
              ref="imageUpload"
              :accept="uploadFile.accept"
              :limit="1"
              :show-chunks="true"
              :multiple="false"
              :is-oss="uploadFile.isOss"
              :chunk-size="uploadFile.chunksize"
              @close="uploadFile.showUpload = -1"
              @success="uploadSuccess"
            >
              <div slot="tip" class="upload-tip">
                <i class="el-icon-info" />
                :
                只能上传：图片文件
              </div>
            </image-no-cropper-upload>
          </template>
          <template v-if="form.source===2" />
        </el-form-item>
        <el-form-item label="跳转链接">
          <el-link type="primary" @click="handleLink">
            {{ form.link && form.link.name ? form.link.name : '选择链接' }}
          </el-link>
          <span v-if="form.link && form.link.name" @click="delLink">
            <i style="vertical-align:middle;" class="el-icon-delete" />
          </span>

        </el-form-item>
        <el-form-item v-for="(item,i) in fields" :key="i" :label="item.name">
          <el-input v-model="form[item.param]" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="visible = false">关 闭</el-button>
        <el-button type="primary" style="padding: 8px 30px;" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!--    从图片库中选择-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      custom-class="live-dialog"
      :visible.sync="showPic"
      title="选择图片"
      width="1200px"
      center
    >
      <library
        @select="handleChoose"
      />
      <div slot="footer" class="dialog-footer">
        <el-button
          type="default"
          style="padding: 10px 30px"
          @click="showPic=false"
        >取 消</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import draggable from 'vuedraggable'
import ImageNoCropperUpload from '@/components/ImageNoCropperUpload'
import library from './library'
import { getToken } from '@/utils/auth'
import { deepClone, randomStringForId } from '@/utils'
export default {
  name: 'VImgData',
  components: { draggable, ImageNoCropperUpload, library },
  inject: ['focusId', 'pageVar', 'focusName', 'getListItemInfo'],
  props: {
    option: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      showPic: false,
      list: [],
      index: 0,
      visible: false,
      form: {
        source: 1,
        pic: '',
        imgId: '',
        imgUrl: '',
        link: '',
        id: randomStringForId(8)
      },
      // title: '',
      // subTitle: '',
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        subTitle: [
          { required: true, message: '请输入副标题', trigger: 'blur' }
        ],
        pic: [
          { required: true, message: '请设置图片', trigger: 'blur' }
        ]
      },
      upload: {
        headers: {
          token: getToken()
        },
        action: `${process.env.VUE_APP_BASE_API}files/upload`,
        result: '',
        loading: false
      },
      result: '',
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: -1, // 1视频 2图片 3附件
        accept: '',
        fileType: '',
        fileIndex: 0,
        isOss: !!sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG')
      },
      fileViewId: '',
      linkFlag: true,
      fields: []
    }
  },
  created() {
    if (this.option.value !== '') {
      try {
        this.list = this.option.value || []
      } catch (e) {}
    }
    if (this.option.field !== undefined) {
      this.setForm()
    }
  },
  methods: {
    delLink() {
      const obj = Object.assign({}, this.form)
      obj.link = ''
      this.$set(this, 'form', obj)
      console.log('this.form', this.form)
    },
    getValue() {
      const obj = {
        [this.option.portName]: {
          code: '200'
        }
      }
      obj[this.option.portName]['data'] = this.list
      return obj
    },
    setValue(k) {
      // this.$set(this, 'list', k)
    },
    setForm() {
      const fields = this.option.field
      this.fields = fields
      fields.forEach(i => {
        if (this.form[i.param] === undefined) {
          this.form[i.param] = ''
        }
      })
    },
    getLinkValue() {
      return this.form.link || ''
    },
    async handleLink() {
      this.linkFlag = false
      const { default: DialogLinks } = await import('@/components/CustomPage/pagemaker/links')
      this.$modal.show(DialogLinks, {
        title: '选择链接',
        type: '',
        compVar: this.getListItemInfo(this.focusName())?.componentVariable ? JSON.parse(this.getListItemInfo(this.focusName()).componentVariable) : [],
        pageVar: this.pageVar(),
        fn: this.linkcomit,
        cn: this.closeLink,
        upValue: this.getLinkValue() === '' ? {} : this.getLinkValue()
      }, {
        width: 800,
        height: 'auto',
        clickToClose: false
      })
    },

    closeLink() {
      this.linkFlag = true
      this.$modal.hideAll()
      return true
    },

    linkcomit(type, name, link, params) {
      this.linkFlag = true
      this.form.link = Object.assign({}, { type, name, link, params })
    },
    setFormPic() {
      if (this.form.source === 1) {
        this.uploadFile.showUpload = 2
      } else {
        this.showPic = true
      }
    },
    sourceChange(e) {
      this.showPic = e === 2
    },
    handleChoose(obj) {
      if (obj.imgURL !== undefined && obj.imgURL !== '') {
        this.form.pic = obj.imgURL
        this.form.imgUrl = obj.imgURL
      } else {
        this.form.imgUrl = ''
        this.form.pic = this.uploadFile.view + obj.imgId
      }
      this.form.imgId = obj.imgId
      this.showPic = false
    },
    beforeupload(file) {
      const _this = this
      const { maxSize } = this
      const size = file.size / 1024 / 1024 <= maxSize
      if (!size) {
        this.$confirm(`文件大小超过${(maxSize)}MB限制`, '提示', {
          confirmButtonText: '重新上传',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false
        }).then(() => {
          _this.$refs.upload.$children[0].handleClick()
        })
      }
      if (size) {
        this.upload.loading = true
      }
      return size
    },

    uploadSuccess(id, files) {
      if (id) {
        this.form.pic = this.uploadFile.isOss ? files[0].ossPath : this.uploadFile.view + id
        this.form.imgId = id
        this.form.imgUrl = this.uploadFile.isOss ? files[0].ossPath : ''
        this.uploadFile.showUpload = -1
        setTimeout(() => {
          this.$refs.form.validateField('pic', (val) => {
            if (!val) {
              return true
            } else {
              return false
            }
          })
        }, 500)
      }
    },

    uploaderror() {
      this.result = 'fail'
    },
    delImg() {
      this.form.pic = ''
    },
    delImg4list(i) {
      this.list.splice(i, 1)
    },
    addImg() {
      this.list.push({
        id: this.list.length,
        imgId: '',
        imgUrl: '',
        title: '',
        subTitle: '',
        id: randomStringForId(8)

      })
    },
    setPic(i, item) {
      if (item.pic) {
        this.form = Object.assign({}, item)
      } else {
        this.form = {
          source: 1,
          pic: '',
          imgId: '',
          imgUrl: '',
          title: '',
          subTitle: '',
          id: randomStringForId(8)
        }
      }
      this.visible = true
      this.index = i
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.list[this.index] = this.form
          this.visible = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/var.scss';
.v-img-item{
  position: relative;
  background: #FAFAFA;
  height: 80px;
  margin: 10px;
  .del-img{
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    right: 0;
    >img{
      height: 100%;
      width: 100%;
    }
  }

}
.add-img{
  background: #FAFAFA;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px;
}
/deep/ .form-uploader {
  position: relative;
  .my-slot{
    display: block;
    padding-left:50px ;
  }
  .el-icon-delete {
    //position: absolute;
    //right: -20px;
    //top: 4px;
    float: right;
    &:hover {
      color: $mainColor;
      transform: scale(1.5);
    }
  }
  .el-image {
    width: 100px;
    height: auto;
  }
}
</style>
